package com.g2.rpc.rpc.protocol;

import com.g2.rpc.common.serialize.Serialization;
import com.g2.rpc.remoting.Client;
import com.g2.rpc.remoting.Transporter;
import com.g2.rpc.rpc.Invoker;
import com.g2.rpc.rpc.Protocol;
import com.g2.rpc.rpc.Response;
import com.g2.rpc.rpc.client.G2ClientInvoker;
import com.g2.rpc.rpc.codec.G2Codec;
import com.g2.rpc.rpc.handler.G2ClientHandler;
import com.g2.rpc.util.SpiUtil;
import com.g2.rpc.util.URIUtils;

import java.net.URI;

/**
 * 描述:
 * ${DESCRIPTION}
 *
 * @author lingjiu.kong
 * @version 1.0
 * @date 2021-03-05 23:21
 */
public class G2Protocol implements Protocol {
    @Override
    public void export() {

    }

    @Override
    public Invoker reference(URI uri) {
        // 1. 找到序列化
        String serializationName = URIUtils.getParam(uri, "serialization");
        Serialization serialization = SpiUtil.load(Serialization.class, serializationName);
        // 2. 编解码器
        G2Codec codec = new G2Codec();
        codec.setDecodeType(Response.class); // 客户端 -- 解码 -- 服务端发送过来的响应
        codec.setSerialization(serialization);
        // 3. 收到响应 处理
        G2ClientHandler trpcClientHandler = new G2ClientHandler();
        // 4. 连接 -- 长连接
        String transporterName = URIUtils.getParam(uri, "transporter");
        Transporter transporter = SpiUtil.load(Transporter.class, transporterName);
        Client connect = transporter.connect(uri, codec, trpcClientHandler);
        // 5. 创建一个invoker 通过网络连接发送数据
        return new G2ClientInvoker(connect, serialization);
    }
}
